package com.sunchangpeng.wechat.core.token;

import com.sunchangpeng.wechat.core.exception.WechatError;
import com.sunchangpeng.wechat.core.http.HttpClient;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;

@Slf4j
public class DefaultAccessTokenHolder extends HttpClient implements AccessTokenHolder {
    private String clientId;
    private String clientSecret;
    private String tokenUrl;

    private AccessToken accessToken;

    public DefaultAccessTokenHolder(String tokenUrl, String clientId, String clientSecret) {
        this(new OkHttpClient(), tokenUrl, clientId, clientSecret);
    }

    public DefaultAccessTokenHolder(OkHttpClient httpClient, String tokenUrl, String clientId, String clientSecret) {
        super(httpClient);
        this.clientId = clientId;
        this.clientSecret = clientSecret;
        this.tokenUrl = tokenUrl;
    }

    private synchronized void pullAccessToken() {
        if (accessToken == null || accessToken.expired()) {
            String accessToken = WechatError.hasEror(http(String.format(this.tokenUrl, this.clientId, this.clientSecret), null).getBodyText());
            if (log.isDebugEnabled()) {
                log.debug("[{}]:fetching a new access token : {}", clientId, accessToken);
            }

            this.accessToken = AccessToken.fromJson(accessToken);
        }
    }

    @Override
    public AccessToken accessToken() {
        if (accessToken == null || accessToken.expired()) {
            pullAccessToken();
        }

        return accessToken;
    }

    @Override
    public void expireToken() {
        accessToken.expireToken();
    }
}
